# -*- coding: utf-8 -*- 

import os, subprocess

@auth.requires_login()
def index():
    """
    example action using the internationalization operator T and flash
    rendered by views/default/index.html or views/generic.html
    """
    jobs=db(db.jobs.id>0).select()
    for j in jobs:
        j.user_email = db(db.auth_user.id==j.submitted_by).select().first().email
    return dict(jobs=jobs)

@auth.requires_login()
def new_job():
    form = crud.create(db.jobs,next=URL(r=request,f='index'))
    return dict(form=form)

@auth.requires_login()
def get_file():
    which_file=request.args[0]
    if which_file == 'stdout' or which_file == 'stderr' or which_file == 'script':
        job_id=request.args[1]
        job=db(db.jobs.id==job_id).select().first()
        if job:
            attach_name = job.job_name
            if which_file == 'script':
                attach_name = attach_name + '.script.sh'
            else:
                attach_name = attach_name + '.' + which_file
            if which_file == 'stdout':
                filename = job.stdout
            elif which_file == 'stderr':
                filename = job.stderr
            else:
                filename = job.script
            response.headers['Content-Disposition']='attachment;filename="%s"' % (attach_name)
            filename=os.path.join(request.folder,'uploads',filename)
            response.stream(filename)
    redirect(URL(r=request,c='plugin_pbs',f='index'))

@auth.requires_login()
def delete():
    db(db.jobs.id==request.vars.job_id).delete()
    session.flash='deleted record'
    p = subprocess.Popen(args=['qdel',request.vars.job_id],stdout=subprocess.PIPE,stderr=subprocess.STDOUT)
    p.wait()
    redirect(URL(r=request,c='plugin_pbs',f='index'))
    

@auth.requires_login()
def download():
    """
    allows downloading of uploaded files
    http://..../[app]/default/download/[filename]
    """
    return response.download(request,db)


@auth.requires_login()
def call():
    """
    exposes services. for example:
    http://..../[app]/default/call/jsonrpc
    decorate with @services.jsonrpc the functions to expose
    supports xml, json, xmlrpc, jsonrpc, amfrpc, rss, csv
    """
    session.forget()
    return service()


